package com.example.gb28181.service;

import com.example.gb28181.enums.SipMethodEnum;
import com.example.gb28181.request.SIPRequestProcessor;
import com.example.gb28181.response.SIPResponseProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.sip.*;
import java.text.ParseException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/7/20
 */
@Component
@Slf4j
public class SIPProcessorObserver implements SipListener {

    /**
     * 请求sip处理器集合
     */
    private static final Map<SipMethodEnum, SIPRequestProcessor> REQUEST_PROCESSOR_MAP = new ConcurrentHashMap<>();

    /**
     * 响应sip处理器集合
     */
    private static final Map<SipMethodEnum, SIPResponseProcessor> RESPONSE_PROCESSOR_MAP = new ConcurrentHashMap<>();

    /**
     * 添加 request订阅
     *
     * @param method    处理方法
     * @param processor 处理程序
     */
    public void addRequestProcessor(SipMethodEnum method, SIPRequestProcessor processor) {
        REQUEST_PROCESSOR_MAP.put(method, processor);
    }


    /**
     * 添加 response订阅
     *
     * @param method    处理方法
     * @param processor 处理程序
     */
    public void addResponseProcessor(SipMethodEnum method, SIPResponseProcessor processor) {
        RESPONSE_PROCESSOR_MAP.put(method, processor);
    }

    @Override
    public void processRequest(RequestEvent requestEvent) {
        //获取sip发送信息的方法
        String method = requestEvent.getRequest().getMethod();
        SIPRequestProcessor sipRequestProcessor = REQUEST_PROCESSOR_MAP.get(SipMethodEnum.getMethodEnumByName(method));
        if (Objects.isNull(sipRequestProcessor)) {
            log.error("【方法：】{}，不支持", method);
            return;
        }
        try {
            sipRequestProcessor.process(requestEvent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void processResponse(ResponseEvent responseEvent) {
        log.info("-------->processResponse:{}", responseEvent);
    }

    @Override
    public void processTimeout(TimeoutEvent timeoutEvent) {
        log.info("-------->processTimeout:{}", timeoutEvent);
    }

    @Override
    public void processIOException(IOExceptionEvent ioExceptionEvent) {
        log.info("-------->processIOException:{}", ioExceptionEvent);
    }

    @Override
    public void processTransactionTerminated(TransactionTerminatedEvent transactionTerminatedEvent) {
        log.info("-------->processTransactionTerminated:{}", transactionTerminatedEvent);
    }

    @Override
    public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) {
        log.info("-------->processDialogTerminated:{}", dialogTerminatedEvent);
    }
}
